package cn.ante.ymcc.security;

import cn.ante.ymcc.domain.Login;
import cn.ante.ymcc.domain.Permission;
import cn.ante.ymcc.dto.LoginJwtInfoDto;
import cn.ante.ymcc.mapper.PermissionMapper;
import cn.ante.ymcc.service.ILoginService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    /**
     * 加载数据库中的认证的用户的信息：用户名，密码，用户的权限列表
     * @param username: 该方法把username传入进来，我们通过username查询用户的信息
    (密码，权限列表等)然后封装成 UserDetails进行返回 ，交给security 。
     */
    @Autowired
    private ILoginService loginService;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //密码是基于BCryptPasswordEncoder加密的密文
        //User是security内部的对象，UserDetails的实现类 ，
        //用来封装用户的基本信息（用户名，密码，权限列表）
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username",username);
        Login login = loginService.selectOne(wrapper);
        if (login != null){
            Long loginId = login.getId();
            // 从数据库拿到权限集合
            List<Permission> permissions = permissionMapper.selectPermissionByUser(loginId);
            List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission ->
                new SimpleGrantedAuthority(permission.getSn())).collect(Collectors.toList());
            // 将用户名和id封装在对象里，返回给认证
            LoginJwtInfoDto loginJwtInfoDto = new LoginJwtInfoDto(login.getId(),login.getUsername());
            return new User(JSON.toJSONString(loginJwtInfoDto),login.getPassword(),login.getEnabled(),
                    login.getAccountNonExpired(),login.getAccountNonExpired(),
                    login.getAccountNonLocked(),authorities);
        }

        return null;
    }
}
